package com.youdoneed.community.forum.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.youdoneed.base.common.JWTUtils;
import com.youdoneed.user.consts.UserConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.youdoneed.community.common.vo.PageData;
import com.youdoneed.community.common.vo.ResultMessage;
import com.youdoneed.community.forum.entity.Forummessage;
import com.youdoneed.community.forum.service.ForumcommentService;
import com.youdoneed.community.forum.service.ForummessageService;
import com.youdoneed.community.forum.service.ForummsglabelrelService;
import com.youdoneed.community.forum.service.ForumuserattentionanotherrelService;
import com.youdoneed.community.forum.vo.CreateMsgVo;
import com.youdoneed.community.forum.vo.EditMsgVo;
import com.youdoneed.community.forum.vo.ForumReportVo;
import com.youdoneed.community.forum.vo.GetNearByMessagesVo;
import com.youdoneed.community.forum.vo.IndexMsgParamVo;
import com.youdoneed.community.forum.vo.QueryMsgsVo;
import com.youdoneed.community.forum.vo.SearchForumMsgsVo;
import com.youdoneed.community.forumConfig.service.ForumconfigurationService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 论坛模块控制器
 *
 * @author lid
 * @date 2017.6.1
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping(value = "/forummessage", method = {RequestMethod.GET, RequestMethod.POST})
@Api(value = "论坛模块控制器", description = "论坛模块相关操作")
public class ForummessageController {

    private static final Logger logger = LoggerFactory.getLogger(ForummessageController.class);

    @Autowired
    ForummessageService forummessageService;

    @Autowired
    ForumcommentService forumcommentService;

    @Autowired
    ForummsglabelrelService forummsglabelrelService;

    @Autowired
    ForumconfigurationService forumconfigurationService;

    @Autowired
    ForumuserattentionanotherrelService forumuserattentionanotherrelService;

    /**
     * 增加帖子的分享次数
     *
     * @param msgId
     * @return ResultMessage
     * @author lid
     * @date 2017.10.31
     */
    @RequestMapping(value = "/addShareCount", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "分享次数加1", value = "分享次数加1")
    public ResultMessage<?> addShareCount(String msgId) {
        forummessageService.addShareCount(msgId);
        return ResultMessage.newSuccess("增加帖子的分享次数成功");
    }

    @RequestMapping(value = "/updateUserInfo", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "用户修改头像后同时修改帖子、点赞、评论的头像", value = "用户修改头像后同时修改帖子、点赞、评论的头像")
    public ResultMessage<?> updateUserInfo(String userId, String nickName, String userHeadUrl,String jobName) {
        forummessageService.updateUserInfo(userId, nickName, userHeadUrl,jobName);
        return ResultMessage.newSuccess("修改用户信息成功");
    }


    /**
     * 通过userid查找附近的帖子（新处理方案）
     *
     * @param vo
     * @return ResultMessage
     * @author lid
     * @date 2017.10.18
     */
    @ResponseBody
    @RequestMapping(value = "/getNearByMsgs", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "通过userid查找附近的帖子", value = "通过userid查找附近的帖子")
    public ResultMessage<List<Forummessage>> getNearByMsgs(@RequestBody GetNearByMessagesVo vo,
                                                           @RequestHeader(value = "Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        if (!StringUtils.hasText(userId)) {
            return ResultMessage.newFailure("获取用户信息失败！");
        }
        logger.info("userId:" + userId);
        return ResultMessage.newSuccess("获取附近帖子成功").setData(forummessageService.getNearByMsgs(vo, userId));
    }

    /**
     * 通过userid查找附近的帖子
     *
     * @param vo
     * @return ResultMessage
     * @author lid
     * @date 2017.6.30
     */
    @ResponseBody
    @RequestMapping(value = "/getNearByMessages", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "通过userid查找附近的帖子", value = "通过userid查找附近的帖子")
    public ResultMessage<List<Forummessage>> getNearByMessages(@RequestBody GetNearByMessagesVo vo,
                                                               @RequestHeader(value = "Authorization") String token) {

        /*String userId = JWTUtils.getTokenUserId(token);
        if(StringUtils.hasText(userId)){
            logger.info("userId:"+userId);
        }

        logger.info("getNearByMessages!");

        if(null == vo){
            return ResultMessage.newFailure("参数为空!");
        }

        if (null == vo.getDistance()) {
            return ResultMessage.newFailure("距离参数为空!");
        }

        //距离单位为米
        double distanceD = vo.getDistance();
        //判断是否有距离设置以及用户是否提供了GPS定位数据
        if ((null != vo.getDistance()) && (null != vo.getUserLatitude()) && (null != vo.getUserLongitude())) {
            logger.info("GPS定位数据以及距离设置数据获取正常！distance=" + vo.getDistance() +
                    ",uerLatitude=" + vo.getUserLatitude() + ",userLongitude=" + vo.getUserLongitude());

            List<Forummessage> listForummessage = forummessageService.getNearByUserMsgsByLabel(userId,
                    distanceD, vo.getUserLongitude(), vo.getUserLatitude(), vo.getBeforeDeadTime(),
                    vo.getLastDeadTime(), vo.getListLabelIds(), vo.getHasLabels());

            if (null == listForummessage) {
                return ResultMessage.newFailure("获取附近帖子失败！");
            }
            return ResultMessage.newSuccess("获取附近帖子成功").setData(listForummessage);
        }

        return ResultMessage.newFailure("GPS定位数据异常！");*/

        String userId = JWTUtils.getTokenUserId(token);
        if (!StringUtils.hasText(userId)) {
            return ResultMessage.newFailure("获取用户信息失败！");
        }
        logger.info("userId:" + userId);
        return ResultMessage.newSuccess("获取附近帖子成功").setData(forummessageService.getNearByMsgs(vo, userId));
    }

    /**
     * 获取首页帖子的第二种实现形式
     *
     * @param vo
     * @return
     * @author lid
     * @date 2017.7.10
     */
    @ResponseBody
    @RequestMapping(value = "/getIndexMsgs", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "通过userid查找首页的帖子", value = "通过userid查找首页的帖子")
    public ResultMessage<List<Forummessage>> getIndexForummessages(@RequestBody IndexMsgParamVo vo, @RequestHeader(value = "Authorization") String token) {
        List<Forummessage> listForummessage = forummessageService.getIndexPageMsgs(vo);
        return ResultMessage.newSuccess("获取帖子列表成功！").setData(listForummessage);
    }

    /**
     * 获取首页帖子的第三种实现形式
     * @param vo
     * @param token
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getIndexPageMsgs", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取首页帖子的第三种实现形式", value = "获取首页帖子的第三种实现形式")
    public ResultMessage<List<Forummessage>> getIndexPageMsgs(@RequestBody IndexMsgParamVo vo, @RequestHeader(value = "Authorization") String token){
        List<Forummessage> listForummessage = forummessageService.getIndexPageMsgs(vo);
        return ResultMessage.newSuccess("获取帖子列表成功！").setData(listForummessage);
    }


    @RequestMapping(value = "/getForummessageByGroupId", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "群组页面调用，通过groupId查找当前群组的帖子", value = "群组页面调用，通过groupId查找当前群组的帖子")
    public ResultMessage<List<Forummessage>> getForummessageByGroupId(String groupId, Integer limit, Integer offset,
                                                                      @RequestHeader(value = "Authorization") String token) {

        logger.info("getForummessageByGroupId!groupId:" + groupId);
        String userId = JWTUtils.getTokenUserId(token);
        if (StringUtils.hasText(userId)) {
            logger.info("userId:" + userId);
        }
        List<Forummessage> listForummessage = forummessageService.selectByGroupId(userId, groupId, limit, offset);
        if (null == listForummessage) {
            return ResultMessage.newFailure("获取群组帖子失败！");
        }
        return ResultMessage.newSuccess("获取群组帖子成功").setData(listForummessage);
    }


    /**
     * 个人主页通过userid获取当前用户已发表的所有帖子信息
     *
     * @param userId
     * @return
     * @author lid
     * @date 2017.6.2
     */
    @RequestMapping(value = "/getForummessageByUserId", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "个人主页调用，通过userid查找当前用户的帖子", value = "个人主页调用，通过userid查找当前用户的帖子")
    public ResultMessage<PageData> getForummessageByUserId(String userId, String searchedUserId, Integer limit, Integer offset,
                                                           @RequestHeader(value = "Authorization") String token) {
        logger.info("getForumcommentByUserId!userId:" + userId + ",searchedUserId:" + searchedUserId);
        PageData page = forummessageService.selectByUserId(userId, searchedUserId, limit, offset);
        return ResultMessage.newSuccess("获取用户帖子成功").setData(page);
    }

    /**
     * 查询被举报的帖子，按举报次数由高到低显示
     * @param name 用户昵称
     * @param msgStruct 消息内容
     * @param createDateS 起始时间
     * @param createDateE 终止时间
     * @return
     * @author hexz
     * @date 2017.6.2
     */
    /*@RequestMapping(value = "/getReportMsg" , method = {RequestMethod.GET , RequestMethod.POST})
    @ApiOperation(notes = "后台查询被举报信息" , value = "后台查询被举报信息")
	public ResultMessage getReportMsg(String name, String msgStruct,String createDateS,String createDateE) {
		logger.info("根据用户名" + name + ",内容" + msgStruct + ",时间段" + createDateS +"-"+createDateE+"查询论坛信息");
		List<Forummessage> forumMsgList = forummessageService.getReportMsg(name, msgStruct, createDateS , createDateE);
		if(null == forumMsgList){
			return ResultMessage.newFailure("获取被举报帖子失败！");
		}
		return ResultMessage.newSuccess("获取被举报帖子成功！").setData(forumMsgList);
	}*/

    /**
     * 用户发帖
     *
     * @param
     * @return
     * @author lid
     * @date 2017.6.2
     */
    @ResponseBody
    @RequestMapping(value = "/publishForumMsg", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "用户发帖", value = "用户发帖")
    public ResultMessage<String> publishForumMessage(@RequestBody CreateMsgVo createMsgVo,
                                                     @RequestHeader(value = "Authorization") String token) {
        String result = forummessageService.publishForumMessage(createMsgVo);
        return ResultMessage.newSuccess("发帖成功").setData(result);
    }

    /**
     * 用户编辑帖子
     *
     * @param
     * @return
     * @author lid
     * @date 2017.6.2
     */
    @ResponseBody
    @RequestMapping(value = "/editForumMessage", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "用户编辑帖子", value = "用户编辑帖子")
    public ResultMessage<?> editForumMessage(@RequestBody EditMsgVo editMsgVo) {
        forummessageService.editForumMessage(editMsgVo);
        return ResultMessage.newSuccess("编辑帖子成功");
    }

    /**
     * 修改推荐状态
     *
     * @param forumMsgId
     * @param recommand
     * @author lid
     * @date 2017.10.12
     */
    @ResponseBody
    @RequestMapping(value = "/updateRecommandStatus", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "修改推荐状态", value = "修改推荐状态")
    public ResultMessage<?> updateRecommandStatus(String forumMsgId, Integer recommand) {
        forummessageService.updateRecommandStatus(forumMsgId, recommand);
        return ResultMessage.newSuccess("修改推荐状态成功");
    }

    /**
     * 后台删除帖子(逻辑删除)
     *
     * @param
     * @return
     * @author hexz
     * @date 2017.6.2
     */
    @RequestMapping(value = "/deleteForumMsg", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台逻辑删除帖子", value = "后台逻辑删除帖子")
    public ResultMessage<Integer> deleteForumMsgById(String forumMsgId) {
        logger.info("开始删除帖子！forumMsgId:" + forumMsgId);
        int sucNum = forummessageService.deleteForumMsgById(forumMsgId);
        return ResultMessage.newSuccess("删除帖子成功！").setData(sucNum);
    }

    /**
     * 后台恢复帖子(逻辑恢复)
     *
     * @param
     * @return
     * @author lid
     * @date 2017.8.2
     */
    @RequestMapping(value = "/regainForumMsgById", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台恢复帖子", value = "后台恢复帖子")
    public ResultMessage<Integer> regainForumMsgById(String forumMsgId) {
        logger.info("开始恢复帖子！forumMsgId:" + forumMsgId);
        int sucNum = forummessageService.regainForumMsgById(forumMsgId);
        return ResultMessage.newSuccess("恢复帖子成功！").setData(sucNum);
    }


    /**
     * 用户删除帖子信息(物理删除)
     *
     * @param
     * @return
     * @author hexz
     * @date 2017.6.2
     */
    @RequestMapping(value = "/deleteForumMsgByUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "用户删除帖子！（物理删除）", value = "用户删除帖子！（物理删除）")
    public ResultMessage<Integer> deleteForumMsgByUser(String forumMsgId) {

        logger.info("物理删除帖子！forumMsgId:" + forumMsgId);
        int sucNum = forummessageService.deleteForumMsgByUser(forumMsgId);
        return ResultMessage.newSuccess("删除帖子成功！").setData(sucNum);
    }

    /**
     * 管理后台分页查看所有帖子
     *
     * @return ResultMessage
     * @author lid
     * @date 2017.6.6
     */
    @ResponseBody
    @RequestMapping(value = "/queryAllForumMsg", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台分页查找所有帖子", value = "后台分页查找所有帖子")
    public ResultMessage<PageData> queryAllForumMsg(@RequestBody QueryMsgsVo vo) {
        PageData mapResult = forummessageService.getAllForummessageByPage(vo);
        if (null == mapResult) {
            return ResultMessage.newFailure("后台分页查找所有帖子失败！");
        }
        return ResultMessage.newSuccess("后台分页查找所有帖子成功！").setData(mapResult);
    }

    /**
     * 根据条件查找帖子
     *
     * @param msgType
     * @param msgContent
     * @param createDateS
     * @param createDateE
     * @return ResultMessage
     * @author lixs
     * @date 2017.6.7
     */
    @RequestMapping(value = "/getFindMsg", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台查询帖子", value = "后台查询帖子")
    public ResultMessage<PageData> getFindMsg(String msgType, String msgContent, String createDateS, String createDateE, Integer limit, Integer offset) {
        logger.info("根据帖子类型" + msgType + ",内容" + msgContent + ",时间段" + createDateS + "-" + createDateE + "查询论坛帖子信息");
        List<Forummessage> MsgList = forummessageService.getForumMsg(msgType, msgContent, createDateS, createDateE);
        List<Forummessage> forumMsgList = forummessageService.getForumMsgByPage(msgType, msgContent, createDateS, createDateE, limit, offset);
        if (null == forumMsgList) {
            return ResultMessage.newFailure("获取帖子失败！");
        }
//        Map<String, Object> mapResult = new HashMap<String, Object>();
//        mapResult.put("rows", forumMsgList);
//        logger.info("获取帖子总数");
//        int total = MsgList.size();
//        logger.info("total:" + total);
//        mapResult.put("total", total);
//        logger.info("mapResult:" + mapResult);
        PageData page = new PageData();
        page.setRows(forumMsgList);
        page.setTotal(MsgList.size());
        return ResultMessage.newSuccess("获取帖子成功！").setData(page);
    }

    /**
     * 根据帖子id获取帖子详情，包括点赞数，点赞人，评论以及评论的评论
     *
     * @param forumMsgId
     * @return Map<String, Object>
     * @author lid
     * @date 2017.6.22
     */

    @RequestMapping(value = "/getForumMsgDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取帖子详情", value = "获取帖子详情")
    public ResultMessage<Forummessage> getForumMsgDetail(String forumMsgId, String userId) {
        logger.info("getForumMsgDetail!forumMsgId:" + forumMsgId);
        Forummessage forummessage = forummessageService.getForumMsgDetail(forumMsgId, userId);
        if (null == forummessage) {
            return ResultMessage.newFailure("该帖子已删除！");
        }
        return ResultMessage.newSuccess("获取帖子详情成功！").setData(forummessage);
    }

    /**
     * 通过指定的若干个标签id查找论坛帖子
     *
     * @param
     * @return ResultMessage
     * @author lid
     */
    @ResponseBody
    @RequestMapping(value = "/searchForumMsgs", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "搜索帖子", value = "搜索帖子")
    public ResultMessage<List<Forummessage>> searchForumMsgs(@RequestBody SearchForumMsgsVo vo) {
        if ((null == vo) || (null == vo.getListMsgLabelIds())) {
            return ResultMessage.newFailure("参数为空");
        }

        List<String> listMsgLabelIds = vo.getListMsgLabelIds();

        logger.info("searchForumMsgs!listMsgLabelIds.size():" + listMsgLabelIds.size());

        int size = listMsgLabelIds.size();
        /**
         * 必须输入标签才能正常搜索
         */
        if (0 == size) {
            return ResultMessage.newFailure("标签信息为空，请输入正确的标签信息");
        }

        /**
         * 控制前台输入的标签不能超过3个
         */
        if (3 < size) {
            return ResultMessage.newFailure("输入的标签不能超过3个，请输入正确的标签信息");
        }

        List<Forummessage> listForummessage = forummessageService.findMsgsByLabels(listMsgLabelIds);
        return ResultMessage.newSuccess("搜索帖子成功").setData(listForummessage);
    }

    /**
     * 管理后台分页查看所有被举报的帖子
     *
     * @return ResultMessage
     * @author lixs
     * @date 2017.6.9
     */
    @RequestMapping(value = "/queryAllReportForumMsg", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "后台分页查找所有被举报帖子", value = "后台分页查找所有被举报帖子")
    public ResultMessage<PageData> queryAllReportForumMsg(String forumHandle, int limit, int offset) {
        List<ForumReportVo> listForummessage = forummessageService.queryAllReportForumMsg(forumHandle, limit, offset);
        PageData page = new PageData();
        page.setRows(listForummessage);
        page.setTotal(forummessageService.countReportMsgs(forumHandle));

        return ResultMessage.newSuccess("后台分页查找所有被举报帖子成功！").setData(page);
    }

    @RequestMapping(value = "/searchMessageByContent", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "根据帖子内容搜索帖子", value = "根据帖子内容搜索帖子")
    public ResultMessage<List<Forummessage>> searchMessageByContent(String content, Integer rows, Integer currentPage,
                                                                    @RequestHeader(value = "Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        if (StringUtils.hasText(userId)) {
            logger.info("userId:" + userId);
        }

        logger.info("根据帖子内容搜索帖子!");
        List<Forummessage> listForummessage = forummessageService.searchMessageByContent(userId, content, rows, currentPage);
        if (null != listForummessage) {
            return ResultMessage.newSuccess("根据帖子内容搜索帖子成功！").setData(listForummessage);
        }
        return ResultMessage.newFailure("根据帖子内容搜索帖子失败！");
    }

    @RequestMapping(value = "/getRecommandMsgByType", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取推荐帖子", value = "获取推荐帖子")
    public ResultMessage<List<Forummessage>> getRecommandMsgByType(String currentMsgId, String msgType, Integer currentPage, Integer rows,
                                                                   @RequestHeader(value = "Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        if (StringUtils.hasText(userId)) {
            logger.info("userId:" + userId);
        }

        List<Forummessage> listForummessage = forummessageService.getRecommandMsgByType(userId, currentMsgId, msgType, currentPage, rows);
        return ResultMessage.newSuccess("获取推荐帖子成功！").setData(listForummessage);
    }

    @RequestMapping(value = "/getAttentionUserMsgByType", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取关注用户的帖子", value = "获取关注用户的帖子")
    public ResultMessage<List<Forummessage>> getAttentionUserMsgByType(String msgType, Date beforeDeadTime, Integer number,
                                                                   @RequestHeader(value = "Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        if (StringUtils.hasText(userId)) {
            logger.info("userId:" + userId);
        }

        List<Forummessage> listForummessage = forummessageService.getAttentionUserMsgByType(userId, msgType, beforeDeadTime, number);
        return ResultMessage.newSuccess("获取推荐帖子成功！").setData(listForummessage);
    }

    @RequestMapping(value = "/getIndexRecommandMsgs", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(notes = "获取首页推荐的3D视频和酷视频", value = "获取首页推荐的3D视频和酷视频")
    public ResultMessage<List<Forummessage>> getIndexRecommandMsgs(@RequestHeader(value = "Authorization") String token) {
        String userId = JWTUtils.getTokenUserId(token);
        if (StringUtils.hasText(userId)) {
            logger.info("userId:" + userId);
        }

        List<Forummessage> listForummessage = forummessageService.getIndexRecommandMsgs(userId);
        return ResultMessage.newSuccess("获取推荐帖子成功！").setData(listForummessage);
    }


    @RequestMapping(value = "/getTotalAttentionMe", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("获取用户被关注的总数（内部接口）")
    public ResultMessage<Integer> getTotalAttentionMe(String userId) {
        logger.info("获取用户被关注的总数");
        int attentionNumber = forumuserattentionanotherrelService.countMyFollower(userId);
        return ResultMessage.newSuccess("获取用户被关注总数成功!").setData(attentionNumber);
    }

    @RequestMapping(value = "/getTotalAgreeMe", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("获取用户被点赞的总数（内部接口）")
    public ResultMessage<Integer> getTotalAgreeMe(String userId) {
        logger.info("获取用户被点赞的总数");
        Integer msgLikePointCount = forummessageService.countLikePointsByUserId(userId);
        logger.info("msgLikePointCount:" + msgLikePointCount);

        Integer commentLikePointCount = forumcommentService.countLikePointsByUserId(userId);
        logger.info("commentLikePointCount:" + commentLikePointCount);

        int totalLikePoint = 0;
        if ((null != msgLikePointCount)
                && (0 < msgLikePointCount)) {
            totalLikePoint = totalLikePoint + msgLikePointCount;
        }

        if ((null != commentLikePointCount)
                && (0 < commentLikePointCount)) {
            totalLikePoint = totalLikePoint + commentLikePointCount;
        }
        return ResultMessage.newSuccess("获取用户被点赞的总数成功！").setData(totalLikePoint);
    }
}


